<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateOfflineUserAPIRequest;
use App\Http\Requests\API\UpdateOfflineUserAPIRequest;
use App\Models\OfflineUser;
use App\Models\ParkInfo;
use App\Repositories\OfflineUserRepository;
use App\Repositories\ParkInfoRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use Illuminate\Support\Facades\DB;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;
use App\Services\OfflineServices;
use Illuminate\Support\Facades\Auth;

/**
 * Class OfflineUserController
 * @package App\Http\Controllers\API
 */

class OfflineUserAPIController extends AppBaseController
{
    /** @var  OfflineUserRepository */
    private $offlineUserRepository;
    use OfflineServices;

    public function __construct(OfflineUserRepository $offlineUserRepo)
    {
        $this->offlineUserRepository = $offlineUserRepo;
    }

    /**
     * Display a listing of the OfflineUser.
     * GET|HEAD /offlineUsers
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $this->offlineUserRepository->pushCriteria(new RequestCriteria($request));
        $this->offlineUserRepository->pushCriteria(new LimitOffsetCriteria($request));
        $offlineUsers = $this->offlineUserRepository->orderBy("id",'desc')->paginate($request->limit);
        foreach ($offlineUsers as &$val) {
            $num = DB::table("offline_users_park")->where("user_id",$val->id)
                ->where("issue", 1)
                ->count();
            $val->park_num = $num;
        }

        return $this->sendResponse($offlineUsers->toArray(), '获取成功');
    }

    /**
     * Store a newly created OfflineUser in storage.
     * POST /offlineUsers
     *
     * @param CreateOfflineUserAPIRequest $request
     *
     * @return Response
     */
    public function store(CreateOfflineUserAPIRequest $request)
    {
        $input = $request->all();
        $input['status']=148;

        $offlineUsers = $this->offlineUserRepository->create($input);

        $offlineUsers->password = config('custom.default_password');
        $offlineUsers->save();

        return $this->sendResponse($offlineUsers->toArray(), 'Offline User saved successfully');
    }

    /**
     * Display the specified OfflineUser.
     * GET|HEAD /offlineUsers/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        /** @var OfflineUser $offlineUser */
        $offlineUser = $this->offlineUserRepository->findWithoutFail($id);

        if (empty($offlineUser)) {
            return $this->sendError('Offline User not found');
        }

        return $this->sendResponse($offlineUser->toArray(), 'Offline User retrieved successfully');
    }

    /**
     * Update the specified OfflineUser in storage.
     * PUT/PATCH /offlineUsers/{id}
     *
     * @param  int $id
     * @param UpdateOfflineUserAPIRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateOfflineUserAPIRequest $request)
    {
        $input = $request->all();

        /** @var OfflineUser $offlineUser */
        $offlineUser = $this->offlineUserRepository->findWithoutFail($id);

        if (empty($offlineUser)) {
            return $this->sendError('数据不存在');
        }

        $offlineUser = $this->offlineUserRepository->update($input, $id);

        return $this->sendResponse($offlineUser->toArray(), '操作成功');
    }

    /**
     * Remove the specified OfflineUser from storage.
     * DELETE /offlineUsers/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        /** @var OfflineUser $offlineUser */
        $offlineUser = $this->offlineUserRepository->findWithoutFail($id);

        if (empty($offlineUser)) {
            return $this->sendError('不存在此用户');
        }

        $num = DB::table("offline_users_park")->where("user_id",$id)
            ->where("issue", 1)
            ->count();
        if($num>0){
            return $this->sendError('请先关闭下发车场');
        }
        $offlineUser->delete();

        return $this->sendResponse($id, 'Offline User deleted successfully');
    }

    /**
     * @param $id
     * @param Request $request
     * @return mixed
     */
    public function changePassword($id, Request $request)
    {
        $this->validate($request,['password'=>'required|string|max:64']);
        $offlineUser = $this->offlineUserRepository->findWithoutFail($id);

        if (empty($offlineUser)) {
            return $this->sendError('用户不存在');
        }

        $offlineUser->password=$request->get('password');
        $offlineUser->save();

        return $this->sendResponse($id, '密码重置成功');

    }

    public function parkList(Request $request){
        $input = $request->all();
        if(!isset($input['id']) && empty($input['id'])){
            return $this->sendError('缺少用户id');
        }
        $id = $input['id'];
        $parks = $this->getUserParks();
        $parks = $this->getParkCodes($parks);
        $res = ParkInfo::whereIn("park_code",$parks)
            ->active()
            ->select(['park_code','parking_name'])
            ->get();
        $offline_park = DB::table("offline_users_park")
            ->where("user_id",$id)
            ->whereIn("park_code",$parks)
            ->select("status","issue","park_code")
            ->get();
        $offline_park = obj2arr($offline_park);
        $park_status_arr = array_column($offline_park,"status","park_code");
        $park_issue_arr = array_column($offline_park,"issue","park_code");

        $res = obj2arr($res);
        foreach ($res as &$val) {
            $val['issue'] = isset($park_issue_arr[$val['park_code']])?$park_issue_arr[$val['park_code']]:'0';
            $val['status'] = isset($park_status_arr[$val['park_code']])?$park_status_arr[$val['park_code']]:'';
        }
        return $this->sendResponse($res, '获取成功');
    }

    public function  issuePark(Request $request){
        $input = $request->all();
        $id = isset($input['id'])?$input['id']:'';
        $offlineUser = $this->offlineUserRepository->findWithoutFail($id);

        // 车场名称
        if(isset($input['park_code']) && !empty($input['park_code'])){
            $park_code = $input['park_code'];
        } else {
            return $this->sendError('缺少park_code');
        }
        $status = $input['status'];
        if(!in_array($input['issue'],[0,1])){
            return $this->sendError('issue参数错误');
        }

        if (empty($offlineUser)) {
            return $this->sendError('用户不存在');
        }
        $user = Auth::user();
        $user = obj2arr($user);

        $data = [];
        $data['park_code'] = $park_code;
        $data['account'] = $offlineUser->name;
        $data['password'] = $offlineUser->password;
        $data['level'] = 1;
        $data['operator'] = $offlineUser->true_name;  //$user['true_name'];
        if($input['issue'] == 0){
            $del_data = [];
            $del_data['park_code'] = $park_code;
            $del_data['account'] =  $offlineUser->name;
            $res = $this->deleteIssueUser($del_data);
            if ($res['code'] == 0) {
                DB::table("offline_users_park")->where("park_code", $park_code)
                    ->where("user_id", $id)
                    ->delete();
                return $this->sendResponse([], '操作成功');
            } else {
                return $this->sendResponse([], '操作失败');
            }
        } else {
            if (empty($status)) {
                $res = $this->sendIssueUser($data);
            } else {
                $res = $this->editIssueUser($data);
            }

            $insert_data = [];
            if ($res['code'] == 0) {
                $insert_data['status'] = 1;
                $op_name = "下发成功";
                $num = $this->getFailureNum($id);
                if ($num > 0) {
                    $this->offlineUserRepository->update(['status' => 227], $id);
                } else {
                    $this->offlineUserRepository->update(['status' => 226], $id);
                }
            } else {
                $insert_data['status'] = 2;
                $op_name = "下发失败";
                $this->offlineUserRepository->update(['status' => 227], $id);
            }
            DB::table("offline_users_park")->where("park_code", $park_code)
                ->where("user_id", $id)
                ->delete();
            $insert_data['park_code'] = $park_code;
            $insert_data['user_id'] = $id;
            $insert_data['issue'] = $input['issue'];
            DB::table("offline_users_park")->insert($insert_data);
        }
        return $this->sendResponse([], '操作成功，'.$op_name);
    }

    function getFailureNum($user_id, $arr=[0,2]){
        return DB::table("offline_users_park")->where("user_id",$user_id)
            ->whereIn("status", $arr)
            ->count();
    }


}
